package com.sdwz.library.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.sdwz.library.entity.BookInfo;
import com.sdwz.library.entity.vo.BookExcelVo;
import com.sdwz.library.entity.vo.BookInfoVo;
import com.sdwz.library.listener.ExcelListener;
import com.sdwz.library.mapper.BookCategoryMapper;
import com.sdwz.library.mapper.BookInfoMapper;
import com.sdwz.library.service.BookInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class BookInfoServiceImpl extends ServiceImpl<BookInfoMapper, BookInfo> implements BookInfoService {

    @Autowired
    private BookCategoryMapper bookCategoryMapper;

    /**
     * 多条件分页查询
     * @param current
     * @param limit
     * @param bookInfoVo
     * @return
     */
    @Override
    public Page<BookInfo> selectBookPage(long current, long limit, BookInfoVo bookInfoVo) {
        Page<BookInfo> page = new Page<>(current,limit);
        QueryWrapper<BookInfo> wrapper = new QueryWrapper<>();
        String id = bookInfoVo.getId();
        String cateId = bookInfoVo.getCateId();
        String bookName = bookInfoVo.getBookName();
        String author = bookInfoVo.getAuthor();
        String press = bookInfoVo.getPress();
        Date createTime = bookInfoVo.getCreateTime();

        if (!Strings.isNullOrEmpty(id)){
            wrapper.eq("id",id);
        }
        if (!Strings.isNullOrEmpty(cateId)){
            wrapper.eq("cate_id",cateId);
        }
        if (!Strings.isNullOrEmpty(bookName)){
            wrapper.like("book_name",bookName);
        }
        if (!Strings.isNullOrEmpty(author)){
            wrapper.eq("author",author);
        }
        if (!Strings.isNullOrEmpty(press)){
            wrapper.like("press",press);
        }
        if (createTime != null){
            wrapper.eq("create_time",createTime);
        }
        wrapper.orderByDesc("create_time");
        Page<BookInfo> bookInfoPage = baseMapper.selectPage(page, wrapper);

        //书籍的额外参数中添加类别信息
        List<BookInfo> records = new ArrayList<>();
        for (BookInfo bookInfo:bookInfoPage.getRecords()){
            String cateId1 = bookInfo.getCateId();
            String cateName = bookCategoryMapper.selectById(cateId1).getCateName();
            Map<String,Object> map = new HashMap<>();
            map.put("cateName",cateName);
            bookInfo.setPrama(map);
            records.add(bookInfo);
        }
        bookInfoPage.setRecords(records);
        return bookInfoPage;
    }

    /**
     * excel数据导入
     * @param file
     */
    @Override
    public void importExcelData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), BookExcelVo.class, new ExcelListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * excel模板导出
     */
    @Override
    public void exportTemplate(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode("bookInfo(请删除模板示例)", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        QueryWrapper<BookInfo> wrapper = new QueryWrapper<>();
        wrapper.last("limit 1");
        BookInfo bookInfo = baseMapper.selectOne(wrapper);

        List<BookExcelVo> bookExcelVoList = new ArrayList<>();
        BookExcelVo bookExcelVo = new BookExcelVo();

        BeanUtils.copyProperties(bookInfo,bookExcelVo);
//        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy.MM.dd");
//        bookExcelVo.setPublicationTime(bookInfo.getPublicationTime().format(fmt));
        bookExcelVoList.add(bookExcelVo);
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), BookExcelVo.class).sheet("dict")
                    .doWrite(bookExcelVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    @Override
//    public void exportTemplate(HttpServletResponse response) {
//        //设置下载信息
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        String fileName = "bookInfo";
//        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
//        //查询数据库
//        List<BookInfo> bookInfoList = baseMapper.selectList(null);
//        //Dict -- DictEeVo
//        List<BookExcelVo> bookExcelVoList = new ArrayList<>();
//        for(BookInfo bookInfo:bookInfoList) {
//            BookExcelVo bookExcelVo = new BookExcelVo();
//            // dictEeVo.setId(dict.getId());
//            BeanUtils.copyProperties(bookInfo,bookExcelVo);
//            bookExcelVoList.add(bookExcelVo);
//        }
//        //调用方法进行写操作
//        try {
//            EasyExcel.write(response.getOutputStream(), BookExcelVo.class).sheet("dict")
//                    .doWrite(bookExcelVoList);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
